/*


 */

package jas.rpc.server;

import jas.rpc.RemoteObject;
import jas.rpc.client.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

/**
 * Reads objects from a stream while translating remote object references to their corresponding Java objects
 * using an object ID bank.
 */
public class RpcServerObjectInputStream extends ObjectInputStream {
    
    private ObjectIdBank ids;
    
    /**
     * Creates an object input stream wrapping the specified stream, translating
     * object references using the specified object ID bank.
     * @param stream the underlying stream to read from.
     * @param ids bank used to associate references in the stream to real objects
     * @throws IOException
     */
    public RpcServerObjectInputStream(InputStream stream, ObjectIdBank ids) throws IOException {
        super(stream);
        this.ids = ids;
        enableResolveObject(true);
    }
    
    @Override
    protected Object resolveObject(Object o) throws IOException {
    	// The java.io.ObjectInputStream class calls this method for each deserialized object.
    	
    	// If a RemoteObject occurs in the stream, replace it by the object it refers to
        if (o != null && o instanceof RemoteObject) {
            RemoteObject remote = (RemoteObject) o;
            return ids.getObjectWithId(remote.getId());
        }
        return o;
    }
    
}
